package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-10
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {


    @Override
    public ResponseResult login(LoginDto dto) {
        // 判断用户名和密码是否为空
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据登录的名称查询数据库是否有该用户
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AdUser::getName, dto.getName());
        AdUser one = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //比对密码
        String pwd = dto.getPassword() + one.getSalt();
        String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if (!md5.equals(one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 密码一致,使用jwt生成token
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", one.getId());
        String token = AppJwtUtil.getToken(userInfo);

        //返回前端数据，排除敏感字段
        HashMap map = new HashMap();
        AdUser user = new AdUser();
        user.setName(one.getName());
        user.setId(one.getId());
        map.put("user", user);
        map.put("token", token);

        return ResponseResult.okResult(map);

    }
}
